//
//  UIViewController+Extension.swift
//  Utility
//
//  Created by 于虎拴 on 2023/4/11.
//
#if os(iOS) || os(tvOS)
import Foundation
import UIKit

extension UIViewController {
  private class var sharedApplication: UIApplication? {
    let selector = NSSelectorFromString("sharedApplication")
    return UIApplication.perform(selector)?.takeUnretainedValue() as? UIApplication
  }
  
  public class var topMost: UIViewController? {
    guard let currentWindows = Self.sharedApplication?.windows else { return nil }
    var rootViewController: UIViewController?
    for window in currentWindows {
      if let windowRootViewController = window.rootViewController, window.isKeyWindow {
        rootViewController = windowRootViewController
        break
      }
    }
    return Self.topMost(of: rootViewController)
  }
  
  public class func topMost(of viewController: UIViewController?) -> UIViewController? {
    // presentedViewController
    if let presentedViewController = viewController?.presentedViewController {
      return Self.topMost(of: presentedViewController)
    }
    
    // UITabBarController
    if let tabBarController = viewController as? UITabBarController,
       let selectedViewController = tabBarController.selectedViewController {
      return Self.topMost(of: selectedViewController)
    }
    
    // UINavigationController
    if let navigationController = viewController as? UINavigationController,
       let visibleViewController = navigationController.visibleViewController {
      return Self.topMost(of: visibleViewController)
    }
    
    // UIPageViewController
    if let pageViewController = viewController as? UIPageViewController,
       pageViewController.viewControllers?.count == 1 {
      return Self.topMost(of: pageViewController)
    }
    
    // childViewController
    for subview in viewController?.view?.subviews ?? [] {
      if let childViewController = subview.next as? UIViewController {
        return Self.topMost(of: childViewController)
      }
    }
    return viewController
  }
}
#endif
